import threading
import time

from flask import Flask, jsonify, request, render_template
from concurrent.futures import ThreadPoolExecutor

app = Flask(__name__)

# 创建线程池
executor = ThreadPoolExecutor(max_workers=3)
# 存储任务结果
task_results = {}
# 用于生成唯一的任务ID
task_counter = 0
# 线程锁
lock = threading.Lock()


def long_running_task(task_id, seconds):
    """模拟耗时任务"""
    time.sleep(seconds)  # 模拟处理时间
    return f"Task {task_id} completed after {seconds} seconds"


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/submit_task", methods=["POST"])
def submit_task():
    global task_counter
    # 获取处理时间参数
    process_time = int(request.json.get("process_time", 5))

    with lock:
        task_counter += 1
        current_task_id = task_counter

    # 提交任务到线程池
    future = executor.submit(long_running_task, current_task_id, process_time)
    task_results[current_task_id] = {
        'status': 'running',
        'future': future
    }

    return jsonify({
        'task_id': current_task_id,
        'message': f'Task {current_task_id} submitted successfully'
    })


@app.route("/task_status/<int:task_id>")
def task_status(task_id):
    if task_id not in task_results:
        return jsonify({
            'status': 'error',
            'message': f'Task {task_id} not found'
        })

    task = task_results[task_id]
    if task['future'].done():
        result = task['future'].result()
        return jsonify({
            'status': 'completed',
            'result': result
        })
    else:
        return jsonify({
            'status': 'running',
            'message': f'Task {task_id} is still running'
        })


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
